﻿using System.Collections;
using System.Text;
using System.Text.RegularExpressions;

namespace Als.Utils.Pay.WeixinPay
{
    public class RequestHandler
    {
        private string DebugInfo;
        private string Key;
        protected Hashtable Parameters = new Hashtable();

        public virtual string CreateMd5Sign(string key, string value)
        {
            StringBuilder builder = new StringBuilder();
            ArrayList list = new ArrayList(this.Parameters.Keys);
            list.Sort();
            foreach (string str in list)
            {
                string strB = (string)this.Parameters[str];
                if ((((strB != null) && ("".CompareTo(strB) != 0)) && ("sign".CompareTo(str) != 0)) && ("key".CompareTo(str) != 0))
                {
                    builder.Append(str + "=" + strB + "&");
                }
            }
            builder.Append(key + "=" + value);
            return MD5Util.GetMD5(builder.ToString(), this.GetCharset()).ToUpper();
        }

        public Hashtable GetAllParameters()
        {
            return this.Parameters;
        }

        protected virtual string GetCharset()
        {
            return "UTF-8";
        }

        public string GetDebugInfo()
        {
            return this.DebugInfo;
        }

        public string GetKey()
        {
            return this.Key;
        }

        public virtual void Init()
        {
        }

        public string ParseXML()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<xml>");
            foreach (string str in this.Parameters.Keys)
            {
                string input = (string)this.Parameters[str];
                if (input == null)
                {
                    input = string.Empty;
                }
                if (Regex.IsMatch(input, "^[0-9.]$"))
                {
                    builder.Append("<" + str + ">" + input + "</" + str + ">");
                }
                else
                {
                    builder.Append("<" + str + "><![CDATA[" + input + "]]></" + str + ">");
                }
            }
            builder.Append("</xml>");
            return builder.ToString();
        }

        public void SetDebugInfo(string debugInfo)
        {
            this.DebugInfo = debugInfo;
        }

        public void SetKey(string key)
        {
            this.Key = key;
        }

        public void SetParameter(string parameter, string parameterValue)
        {
            if ((parameter != null) && (parameter != ""))
            {
                if (this.Parameters.Contains(parameter))
                {
                    this.Parameters.Remove(parameter);
                }
                this.Parameters.Add(parameter, parameterValue);
            }
        }
    }
}
